package cn.xuexiyuan.kpi.controller;

import cn.xuexiyuan.kpi.entity.NodeEntity;
import cn.xuexiyuan.kpi.entity.ResponseEntity;
import cn.xuexiyuan.kpi.mapper.NodeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/node")
public class NodeController {

    @Autowired
    NodeMapper nodeMapper;

    @RequestMapping("/listAll")
    public ResponseEntity listAll() {
        return ResponseEntity.buildSucess(nodeMapper.listAll());
    }


    @RequestMapping("/tree")
    public ResponseEntity tree() {
        List<NodeEntity> list = new ArrayList<>();

        List<NodeEntity> nodes = nodeMapper.listAll();
        Map<Integer, NodeEntity> map = new HashMap<>();
        for (NodeEntity node : nodes){
            if(node.getFather_id() == null){
                list.add(node);
            }
            map.put(node.getId(), node);
        }


        for(Integer key : map.keySet()){
            NodeEntity node = map.get(key);
            Integer father_id = node.getFather_id();
            if(father_id == null || map.get(father_id) == null){
                continue;
            }

            if(null == map.get(father_id).getChildren()){
                map.get(father_id).setChildren(new ArrayList<>());
            }
            map.get(father_id).getChildren().add(node);
        }

        return ResponseEntity.buildSucess(list);
    }

    @RequestMapping("/save")
    public ResponseEntity save(@RequestBody NodeEntity node) {
        nodeMapper.insert(node);
        return ResponseEntity.buildSucess(node, "保存成功", null);
    }

    @RequestMapping("/delete")
    public ResponseEntity delete(@RequestBody NodeEntity param) {
        nodeMapper.delete(param);
        return ResponseEntity.buildSucess(null, "删除成功", null);
    }

}
